package com.michale.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.michale.common.constants.HttpPrefixConstant;
import com.michale.common.constants.UserConstant;
import com.michale.common.domain.model.TreeSelect;
import com.michale.common.domain.permissions.MenuEntity;
import com.michale.common.domain.permissions.RoleEntity;
import com.michale.common.utils.String.StringUtils;
import com.michale.common.utils.security.SecurityUtils;
import com.michale.system.mapper.permissions.MenuMapper;
import com.michale.system.mapper.permissions.RoleMapper;
import com.michale.system.service.MenuService;
import com.michale.system.vo.login.MetaVo;
import com.michale.system.vo.login.RouterVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author Michale
 * @apiNote  菜单权限管理 业务层
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements MenuService {

    @Resource
    private RoleMapper roleMapper;

    /**
     * 根据用户查询系统菜单列表
     *
     * @param menuEntity 菜单信息
     * @return 菜单列表
     */
    @Override
    public List<MenuEntity> selectMenuList(MenuEntity menuEntity) {
        List<MenuEntity> menuList;
        if (SecurityUtils.isAdmin(SecurityUtils.getUserIdentity())) {
            menuList = baseMapper.selectMenuList(menuEntity);
        } else {
            menuEntity.setUserId(SecurityUtils.getUserId());
            menuList = baseMapper.selectMenuListByUserId(menuEntity);
        }
        return menuList;
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     * @return 菜单信息
     */
    @Override
    public MenuEntity selectMenuById(Long menuId) {
        return baseMapper.selectMenuById(menuId);
    }

    /**
     * 新增菜单信息
     *
     * @param menuEntity 菜单信息
     * @return 结果
     */
    @Override
    public int insertMenu(MenuEntity menuEntity) {
        return baseMapper.insertMenu(menuEntity);
    }

    /**
     * 修改菜单信息
     *
     * @param menuEntity 菜单信息
     * @return 结果
     */
    @Override
    public int updateMenu(MenuEntity menuEntity) {
        return baseMapper.updateMenu(menuEntity);
    }

    /**
     * 删除菜单
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public int deleteMenuById(Long menuId) {
        return baseMapper.deleteMenuById(menuId);
    }

    /**
     * 根据角色ID-查询权限
     *
     * @param roleId 角色Id
     * @return 菜单权限
     */
    @Override
    public Set<String> selectMenuPermsByRoleId(Long roleId) {
        List<String> perms = baseMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID-查询权限
     *
     * @param userId 用户Id
     * @return 菜单权限
     */
    @Override
    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = baseMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 通过用户ID获取菜单路由信息
     *
     * @param userId 用户ID
     * @return 菜单路由信息
     */
    @Override
    public List<MenuEntity> selectMenuTreeByUserId(Long userId) {
        List<MenuEntity> menuEntityList;
        if (SecurityUtils.isAdmin(SecurityUtils.getUserIdentity())) {
            //获取所有的菜单列表
            menuEntityList = baseMapper.selectMenuTreeAll();
        } else {
            //根据登录者ID查询菜单列表
            menuEntityList = baseMapper.selectMenuTreeByUserId(userId);
        }
        //封装子路由
        return buildMenuTree(menuEntityList);
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menuEntityList 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<MenuEntity> menuEntityList) {
        List<RouterVo> routers = new LinkedList<>();
        for (MenuEntity menu : menuEntityList) {
            RouterVo router = new RouterVo();
            router.setHidden(UserConstant.HIDDEN.equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
            //当你一个路由下面的 children 声明的路由大于1个时，自动会变成嵌套的模式--如组件页面
            List<MenuEntity> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && UserConstant.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect(UserConstant.REDIRECT);
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo routerVo = new RouterVo();
                routerVo.setPath(menu.getPath());
                routerVo.setComponent(menu.getComponent());
                routerVo.setName(StringUtils.capitalize(menu.getPath()));
                routerVo.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                routerVo.setQuery(menu.getQuery());
                childrenList.add(routerVo);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstant.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean hasChildByMenuId(Long menuId) {
        int count = baseMapper.hasChildByMenuId(menuId);
        return count > 0;
    }

    /**
     * 查询菜单是否存在角色
     *
     * @param menuId 菜单ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkMenuExistRole(Long menuId) {
        int result = baseMapper.checkMenuExistRole(menuId);
        return result > 0;
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menuEntity 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(MenuEntity menuEntity) {
        long menuId = StringUtils.isNull(menuEntity.getMenuId()) ? -1L : menuEntity.getMenuId();
        MenuEntity info = baseMapper.checkMenuNameUnique(menuEntity.getMenuName(), menuEntity.getParentId());
        if (StringUtils.isNotNull(info) && info.getMenuId() != menuId) {
            return UserConstant.NOT_UNIQUE;
        }
        return UserConstant.UNIQUE;
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     * @return 选中菜单列表
     */
    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        RoleEntity roleEntity = roleMapper.selectRoleById(roleId);
        return baseMapper.selectMenuListByRoleId(roleId, roleEntity.isMenuCheckStrictly());
    }

    /**
     * 构建前端添加角色添加菜单所需要树结构-3
     *
     * @param menuEntity 登录者ID
     * @return 菜单列表
     */
    @Override
    public List<TreeSelect> selectMenuTreeList(MenuEntity menuEntity) {
        List<MenuEntity> menuEntityList = selectMenuList(menuEntity);
        return buildMenuTreeSelect(menuEntityList);
    }

    /**
     * 构建前端添加角色添加菜单所需要树结构-2
     *
     * @param menuEntityList 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<MenuEntity> menuEntityList) {
        List<MenuEntity> menuTrees = buildMenuTree(menuEntityList);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 获取组件类型
     *
     * @param menu 菜单
     * @return 组件类型(LAYOUT INNER_LINK PARENT_VIEW)
     */
    public String getComponent(MenuEntity menu) {
        String component = UserConstant.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstant.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstant.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 构建前端需要菜单三级分类
     *
     * @param menuEntityList 菜单列表
     * @return 菜单树列表
     */
    public List<MenuEntity> buildMenuTree(List<MenuEntity> menuEntityList) {
        // 1 查出所有分类
        // 2 组装成父子的树形结构
        return menuEntityList.stream()
                .filter(menuEntity -> menuEntity.getParentId() == 0 //通过ParentCid = 0找出一级分类
                ).peek(item -> {
                    item.setChildren(getChildren(item, menuEntityList));//获取二级分类
                }).sorted(Comparator.comparingInt(menu -> (menu.getOrderNum() == null ? 0 : menu.getOrderNum()))).collect(Collectors.toList());
    }

    /**
     * 从allList中获取root子分类
     *
     * @param menuEntity 菜单列信息
     * @param allList 菜单列表集合
     * @return 菜单列表集合
     */
    private List<MenuEntity> getChildren(MenuEntity menuEntity, List<MenuEntity> allList) {
        return allList.stream()
                .filter(menu -> menu.getParentId().equals(menuEntity.getMenuId())//通过当前商品的父Id == 一级分类的ID查找子分类
                ).peek(item -> {
                    item.setChildren(getChildren(item, allList));//获取三级分类
                }).sorted(Comparator.comparingInt(menu -> (menu.getOrderNum() == null ? 0 : menu.getOrderNum()))).collect(Collectors.toList());
    }

    /**
     * 获取路由地址
     *
     * @param menuEntity 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(MenuEntity menuEntity) {
        String routerPath = menuEntity.getPath();
        // 内链打开外网方式
        if (menuEntity.getParentId().intValue() != 0 && isInnerLink(menuEntity)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menuEntity.getParentId().intValue() && UserConstant.TYPE_DIR.equals(menuEntity.getMenuType())
                && UserConstant.NO_FRAME.equals(menuEntity.getIsFrame())) {
            routerPath = "/" + menuEntity.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menuEntity)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(MenuEntity menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(MenuEntity menu) {
        return menu.getParentId().intValue() == 0 && UserConstant.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstant.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(MenuEntity menu) {
        return menu.getIsFrame().equals(UserConstant.NO_FRAME) && StringUtils.isHttp(menu.getPath());
    }

    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{HttpPrefixConstant.HTTP, HttpPrefixConstant.HTTPS, HttpPrefixConstant.WWW, "."},
                new String[]{"", "", "", "/"});
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(MenuEntity menu) {
        return menu.getParentId().intValue() != 0 && UserConstant.TYPE_DIR.equals(menu.getMenuType());
    }
}
